package com.yzx.lifeassistants.model.impl;

import java.util.List;
import java.util.Properties;

import android.content.Context;

import com.yzx.lifeassistants.bean.Book;
import com.yzx.lifeassistants.model.IQueryBook;
import com.yzx.lifeassistants.model.analysis.QueryBookAnalysis;
import com.yzx.lifeassistants.model.callback.IQueryBookCB;
import com.yzx.lifeassistants.utils.HttpClientUtil;
import com.yzx.lifeassistants.utils.IHttpCallBack;
import com.yzx.lifeassistants.utils.LogcatUtils;
import com.yzx.lifeassistants.utils.PropertyUtil;

/**
 * @Description: 图书检索
 * @author: yzx
 * @time: 2016-3-8 上午10:05:05
 */
public class QueryBookImpl implements IQueryBook {
	public static final String TAG = "queryBookImpl";
	private String url;// URL
	private IQueryBookCB queryCallBack;// 回调

	public QueryBookImpl(Context context, IQueryBookCB queryCallBack) {
		this.queryCallBack = queryCallBack;
		Properties properties = PropertyUtil.getProperties(context,
				"base.properties");
		url = properties.getProperty("query_book_url");
	}

	/**
	 * 
	 * @Description: 通过书名/作者按页检索图书
	 */
	@Override
	public void queryBook(final String key, final int page) {
		HttpClientUtil.sendRequest(url + "?key=" + key + "&page=" + page, null,
				new IHttpCallBack() {

					@Override
					public void onFinish(String response) {
						LogcatUtils.i(response);
						if (QueryBookAnalysis.isNull(response)) {// 返回结果为空
							LogcatUtils.e("QueryBookImpl", "检索图书结果为空");
							queryCallBack.querySuccess(null,
									IQueryBookCB.RESULR_NULL);
						} else {// 返回结果不为空
							LogcatUtils.i("QueryBookImpl", "检索图书成功");
							List<Book> books = QueryBookAnalysis
									.getData(response);
							if (null == books || 1 > books.size()) {
								queryCallBack.querySuccess(null,
										IQueryBookCB.RESULR_NULL);
							} else {
								queryCallBack.querySuccess(books,
										IQueryBookCB.QUERY_SUCCESS);
							}
						}

					}

					@Override
					public void onError(Exception e) {
						if (null != e.getMessage()) {
							LogcatUtils.e("QueryBookImpl", e.getMessage());
						}
						queryCallBack.queryError();
					}
				});
	}
}
